/**
 * @file    md_crc16.c
 * @brief   算法库-MODBUS CRC16校验算法
 * @author  Liuwei
 * @version 1.0.1
 * @date    2023-04-26
 * 
 * @copyright Copyright (c) 2023 JBD-Energy Storage Technology Co. LTD
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version   <th>Author   <th>Description
 * <tr><td>2023-04-26 <td>1.0.1     <td>Liuwei   <td>首次创建
 * </table>
 */

/* includes ------------------------------------------------------------------*/
#include "md_crc16.h"
/* macro/define --------------------------------------------------------------*/

/* typedef -------------------------------------------------------------------*/

/* local functions -----------------------------------------------------------*/

/* static variables ----------------------------------------------------------*/

/* global variables ----------------------------------------------------------*/

/** ------------------------------------------------------------------------- *
  *                             Global function
 ** ------------------------------------------------------------------------- */
/**
 * @brief  计算CRC16
 * @param  buf : 计算缓冲区 
 * @param  len : 计算长度
 * @return uint8_t 
 */
uint16_t md_crc16_calc(uint8_t *buf , uint16_t len)
{
    uint16_t crc = 0xFFFF;
    uint8_t idx = 0;
    uint8_t i = 0;
	
    for (idx = 0; idx < len; ++ idx)
    {
        crc ^= (uint16_t)buf[idx]; // XOR byte into least sig. byte of crc
        for (i = 8; i != 0; -- i)   // Loop over each bit
        {
            if ((crc & 0x0001) != 0)   
            {
                crc >>= 1; 
                crc ^= 0xA001;
            }
            else 
            {
                crc >>= 1;    
            }
        }
    }
 
    crc = ((crc & 0x00ff) << 8) | ((crc & 0xff00) >> 8);
	
	return crc;
}

/** ------------------------------------------------------------------------- *
  *                              Local function
 ** ------------------------------------------------------------------------- */
 
/********** Copyright (c) 2023 JBD-Energy Storage Technology Co. LTD *********/


